package com.meals.system.config.handler;

import com.meals.system.common.Constants;
import com.meals.system.common.ServiceResultEnum;
import com.meals.system.common.SystemException;
import com.meals.system.config.annotation.TokenToAdminUser;
import com.meals.system.dao.WhitesMealAdminUserTokenMapper;
import com.meals.system.entity.AdminUserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Description:
 * Parm:
 * return:
 * Author: Chen
 * Date: 2021/12/21
 */
@Component
public class TokenToAdminUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private WhitesMealAdminUserTokenMapper whitesMealAdminUserTokenMapper;
    public TokenToAdminUserMethodArgumentResolver(){

    }
    public boolean supportsParameter(MethodParameter parameter){
        if (parameter.hasParameterAnnotation(TokenToAdminUser.class)){
            return true;
        }
        return false;
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory){
        if (parameter.getParameterAnnotation(TokenToAdminUser.class) instanceof TokenToAdminUser){
            String token = webRequest.getHeader("token");
            if (null != token && !"".equals(token) && token.length() == Constants.TOKEN_LENGTH){
                AdminUserToken adminUserToken = whitesMealAdminUserTokenMapper.selectByToken(token);
                if (adminUserToken == null){
                    SystemException.fail(ServiceResultEnum.ADMIN_NOT_LOGIN_ERROR.getResult());
                } else if (adminUserToken.getExpireTime().getTime() <= System.currentTimeMillis()){
                    SystemException.fail(ServiceResultEnum.ADMIN_TOKEN_EXPIRE_ERROR.getResult());
                }
                return adminUserToken;
            }else{
                SystemException.fail(ServiceResultEnum.ADMIN_TOKEN_EXPIRE_ERROR.getResult());
            }

        }
        return null;
    }
}
